package cn.mooncode.basketballManage.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * @program: basketballManage
 * @description: 七牛云上传图片到服务器
 * @author: jinweizhi
 * @create: 2021-03-29 15:18
 **/

public class QiniuUploadUtils {

    //    设置公钥与私钥
    private static final String ACCESS_KEY = VariableName.accessKey;
    private static final String SECRET_KEY = VariableName.secretKey;
    //    上传空间
    private static final String bucketName = VariableName.bucket;
    //    图片外链地址
    private static final String DOMAIN = VariableName.domain;

    //    密钥配置
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    private static final Configuration configuration = new Configuration(Zone.huadong());

    //    创建上传对象
    private static final UploadManager uploadManager = new UploadManager(configuration);

    /**
     * 简单上传
     *
     * @return
     */
    public static String getUpload() {
        return auth.uploadToken(bucketName);
    }

    /**
     * 上传图片
     *
     * @param data
     * @return
     */
    public static String upLoadImage(byte[] data) {
        //图片的外链地址
        StringBuffer domain = new StringBuffer(DOMAIN);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        String upToken = getUpload();
        try {
            //上传文件
            Response response = uploadManager.put(data, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet);
            domain.append(putRet.key);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                ex2.printStackTrace();
            }
        }
        return domain.toString();
    }

}
